const SpiderBaseClass = require('./SpiderBaseClass');
const crypto = require('crypto');
const _ = require('lodash');

const listSize = 120;//列表页面有多少个主播信息
class SpiderDouYu extends SpiderBaseClass {

  static firstListPage() {
    return 1;
  }

  /**
   * 获取其它页码的列表页面
   * @param page
   */
  static async getListPage(page) {
    const res = await SpiderDouYu.get(SpiderDouYu.listPageUrl(page),
        {
          dataType: 'json',
          headers: SpiderDouYu.headers('https://www.douyu.com'),
        });

    const data = SpiderDouYu.parseListPage(res, page);
    data.page = page;
    data.nextPage = page + 1;
    data.hasNextPage = page < res.data.data.pgcnt;
    return data;
  }

  static async getTagPage(page, tag) {
    // console.log('getTagPage', page, tag.key);
    const res = await SpiderDouYu.get(SpiderDouYu.listPageUrl(page, tag.key),
        {
          dataType: 'json',
          headers: SpiderDouYu.headers('https://www.douyu.com'),
        });
    const data = SpiderDouYu.parseListPage(res, page);
    data.page = page;
    data.nextPage = page + 1;
    return data;
  }

  static parseListPage(res, page) {
    if (_.isEmpty(res.data.data.rl))
      throw new Error('列表没有数据');

    const list = res.data.data.rl.map(room => {
      return {
        anchor: {
          room: room.rid,
          name: room.nn,
          gender: 0,
          avatar: null,
        },
        type: room.c2name,
        data: {
          num_watch: SpiderDouYu.toNumber(room.ol),
          num_live: 0,
          num_follower: 0,
          num_gift: 0,
        },
      };
    });
    return {
      list,
      getMoreInfo: true,
      hasNextPage: page < res.data.data.pgcnt,
    };
  }

  /**
   * 获取直播间信息
   * @param room
   */
  static async getRoom(room) {
    const res = await SpiderDouYu.get(SpiderDouYu.roomUrl(room.anchor.room),
        {
          dataType: 'json',
          headers: SpiderDouYu.headers('https://www.douyu.com'),
        });
    const data = res.data.data;
    room.type = data.game_name;
    room.anchor.avatar = data.owner_avatar;
    room.data.num_follower = SpiderDouYu.toNumber(data.fans);
    room.data.num_watch = SpiderDouYu.toNumber(data.online);
  }

  /**
   * 生成列表页面的网址
   * @param page
   * @param key
   * @return string
   */
  static listPageUrl(page, key = '0_0') {
    return 'https://www.douyu.com/gapi/rkc/directory/' + key + '/' + page;
  }

  /**
   * 生成直播间信息的网址
   * @param id
   * @return string
   */
  static roomUrl(id) {
    const args = `room/${id}?aid=wp&client_sys=wp&time=${Date.now()}`;
    const auth = crypto.createHash('md5').
        update(args + 'zNzMV1y4EMxOHS6I5WKm').
        digest('hex');
    return 'https://www.douyutv.com/api/v1/' + args + '&auth=' + auth;
  }

}

module.exports = SpiderDouYu;